package com.zhenhunfan.io.model.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * <p>Title: Handler</p>
 * <p>Description: </p>
 *
 * @author zhenhunfan
 * @version 1.0.0
 * @date 2021/4/6
 */
public class Handler extends ChannelInboundHandlerAdapter {
    /**
     * 当有读数据的时候进行处理，以下处理服务端把客户端传递过来的数据打印出来，并且在写回客户端
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server: channel read");
        ByteBuf buf = (ByteBuf)msg;
        System.out.println(buf.toString(CharsetUtil.UTF_8));
        ctx.writeAndFlush(msg);
        //断开通道连接
        //ctx.close();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        //通道一旦产生异常，需要把通道关闭
        //有些时候产生了异常需要写回给客户端
        ctx.close();
    }
}
